package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import Control.CUserComment;

/**
 * Servlet implementation class Comment
 */
public class Comment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Comment() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			Map map = request.getParameterMap();

			int Type = 0;
			String hID = request.getParameter("HID");
			int HID = Integer.parseInt(hID);
			CUserComment cuc = new CUserComment();

			if (map.containsKey("Mark")) {
				Type = 3;

			} else if (map.containsKey("UID")) {
				Type = 1;

			} else if (map.containsKey("HID")) {
				Type = 2;

			}
			switch (Type) {
			 default:
				;
				;
				break;
			case 1: {
				String uID = request.getParameter("UID");
				int UID = Integer.parseInt(uID);
				out.print(cuc.checkComment(HID, UID));
			}
				;
				break;
			case 2: {
				JSONObject json = new JSONObject();
				int[] stars = cuc.getStar(HID);
				json.accumulate("One", stars[0]);
				json.accumulate("Two", stars[1]);
				json.accumulate("Three", stars[2]);
				json.accumulate("Four", stars[3]);
				json.accumulate("Five", stars[4]);
				out.print(json);
			}
				;
				break;
			case 3: {
				String mark = request.getParameter("Mark");
				int Mark = Integer.parseInt(mark);
				String uID = request.getParameter("UID");
				int UID = Integer.parseInt(uID);
				out.print(cuc.insertComment(HID, UID, Mark));
			}
				;
				break;
			}
		} finally {

			out.close();
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
